<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types = 1);

namespace app\shop_admin\model;

use app\index\model\OrderCommodityAttach;
use app\SearchModel;

class AttachValue extends SearchModel
{
    protected $autoWriteTimestamp = false;

    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }

    /**
     * 获取附加属性库存
     * @param $id int 附加属性id
     * @param $return boolean 是否返回附加元素
     * @return int 库存数
     */
    public static function getSell($id, $return = false)
    {
        $count = OrderCommodityAttach::where([
            'attach_id' => $id,
            'status' => 1
        ])->sum('num');
        
        $actval = AttachValue::find($id);
        $stock = $actval['stock'] - $count;

        if (!$return) {
            return $stock;
        }
        return [$stock, $actval];
    }

    public function attachName()
    {
        return $this->belongsTo(AttachName::class, 'attach_name_id', 'id');
    }
}
